<?php
// +----------------------------------------------------------------------
// | Bwsaas
// +----------------------------------------------------------------------
// | Copyright (c) 2015~2020 http://www.buwangyun.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Gitee ( https://gitee.com/buwangyun/bwsaas )
// +----------------------------------------------------------------------
// | Author: buwangyun <hnlg666@163.com>
// +----------------------------------------------------------------------
// | Date: 2020-9-28 10:55:00
// +----------------------------------------------------------------------

namespace app\manage\controller\member;

use buwang\base\MemberBaseController;
use think\App;
use app\Request;
use buwang\traits\JwtTrait;
use think\facade\View;
use app\manage\model\AuthGroupNode;
use app\manage\model\AuthGroup;
use app\manage\model\AuthNode;
use app\manage\model\Admin as AdminModel;
use app\manage\model\AuthGroupAccess;
use app\manage\model\Member;
use app\manage\model\Token;
use buwang\service\UserService;

class Login extends MemberBaseController
{

    // 获取后台菜单初始化数据
    public function getSystemInit(Request $request)
    {

        $admin = $request->userInfo();
        // var_dump( $this->request->user);
        //TODO :得到登录管理员id
        $member_id = $admin['id'];  //id=1为超级管理员，拥有全部权限
        $homeInfo = [
            'title' => '首页',
            'href' => '/manage/member.index/dashboard',
        ];
        $logoInfo = [
            'title' => $admin['nickname'],
            'image' => '/layui/images/logo.png',
            'href' => '/'
        ];
        $menuInfo = Member::getMenuList($member_id);
        $systemInit = [
            'homeInfo' => $homeInfo,
            'logoInfo' => $logoInfo,
            'menuInfo' => $menuInfo,
        ];
        return json($systemInit);
    }


//    public function user(Request $request)
//    {
//         $user = $request->userInfo();
//        $member_id =  $user['id'];
//
//        //$member_id = 2;
//        //当前租户id
//        $list = AuthGroupAccess::getMemberlist($member_id, true);
//        var_dump($list);die;
//        //var_dump($list);die;
//        return view('', ['list' => $list]);
//    }


    public function user()
    {

        $member_id = $this->uid;

        $Member = Member::getTop($member_id);
        if (request()->isAjax()) {
            $page = request()->get('page/d', 1);
            $limit = request()->get('limit/d', 10);

            //TODO 获取搜索条件
            //TODO 如果有不属于表内的字段,查询会报错
            $where = request()->get();
            unset($where['page']);
            unset($where['limit']);
            foreach ($where as $k => $v) {
                if (!$v && $v !== '0' && $v !== 0 && $v !== false) {
                    unset($where[$k]);
                }
            }

            try {
                //得到所有登录用户
                $groups = Member::valiWhere()
                    ->where($where)
                    ->where(function ($query) use ($member_id) {
                        $query->where('parent_id', $member_id)->whereOr('id', $member_id);
                    })
                    ->page($page, $limit)
                    ->order('id desc')->select()->toArray();

                $memberConfigIds = array();
                //组合树
                foreach ($groups as $val) {
                    $memberConfigIds[] = $val['id'];
                }

                $total = Member::valiWhere()
                    ->where($where)
                    ->where(function ($query) use ($member_id) {
                        $query->where('parent_id', $member_id)->whereOr('id', $member_id);;
                    })
                    ->count();
                //返回数据
                $list = array();
                foreach ($groups as $group) {
                    $data = $group;
                    $data['my'] = false;
                    $data['is_top'] = false;
                    if ($group['id'] == $member_id) $data['my'] = true;
                    if ($group['id'] == $Member['id']) $data['is_top'] = true;
                    $data['rules'] = [];
                    $data['auth_group_access'] = [];
                    //查询所有角色，以逗号拼接
                    $rules = AuthGroupAccess::valiWhere()->where('uid', $group['id'])->where('scopes', 'member')->column('group_id');
                    $names = AuthGroupAccess::valiWhere()->where('uid', $group['id'])->where('scopes', 'member')->column('name');
                    if ($rules) {
                        $data['rules'] = $rules;
                    }
                    if ($names) {
                        $data['auth_group_access'] = $names;
                    }
                    //列表中不存在该父id则父id为0
                    if (!in_array($group['parent_id'], $memberConfigIds)) $data['parent_id'] = 0;
                    $list[] = $data;
                }
                $list = array_merge(AuthNode::tree($list, 'id', 'id', 'parent_id'));
            } catch (\think\db\exception\PDOException $e) {
                return $this->error('查询失败', ['errorMsg' => $e->getData()]);
            }

            $data = compact("total", 'list');
            return $this->success('successful', $data);
        }

        return view('');
    }


    /**
     * 编辑管理组
     * @return \think\response\View
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function edit()
    {
        $member_id = $this->uid;

        $Member = Member::getTop($member_id);
        //var_dump( bw_config('wetchatopen.aes_key'));
        if ($this->request->isPost()) {
            if ($member_id != $Member['id']) return $this->error('子租户无权操作');
            $param = $this->request->param();
            $result = Member::updateAdmin($param, true);
            if ($result) {
                return $this->success('操作成功');
            } else {
                return $this->error(Member::getError());
            }
        }
        $id = $this->request->get('id');
        $data = AuthGroupAccess::getMemberFind($id);
        $list = Member::select()->toArray();
        // var_dump($list);die;
        return view('form', ['data' => $data, 'list' => $list]);

    }

    /**
     * 添加管理组
     * @return \think\response\View
     */
    public function add(Request $request)
    {
        $member_id = $this->uid;

        $Member = Member::getTop($member_id);
        $user = $request->userInfo();
        $member_id = $user['id'];
        if ($this->request->isPost()) {
            if ($member_id != $Member['id']) return $this->error('子租户无权操作');
            $param = $this->request->param();

            $param['username'] = $param['nickname'] = 'bw' . $param['mobile'];
            $param['safe_password'] = '123456';

            $result = Member::createAdmin($param, $member_id, true);
            if ($result) {
                // xn_add_admin_log('添加管理组');
                return $this->success('操作成功');
            } else {
                return $this->error(Member::getError());
            }
        }
        return view('form');
    }


    /**
     * 删除
     * @menu true
     * @param int $ids 主键,删除多行时,拼接
     */
    public function delete($ids = 0)
    {
        $member_id = $this->uid;

        $Member = Member::getTop($member_id);

        if (request()->isPost()) {
            if (!$ids) return $this->error('参数有误');
            $list = Member::where('id', 'in', $ids)->where('parent_id', '=', $Member['id'])->select();
            if (!$list) return $this->error('记录不存在');
            if ($member_id != $Member['id']) return $this->error('子租户无权操作');
            Member::startTrans();
            try {
                foreach ($list as $item) {
                    Member::destroy($item['id']);
                    //删除角色中间表
                    $ids = AuthGroupAccess::where('uid', $item['id'])->where('scopes', 'member')->column('id');
                    if ($ids) {
                        AuthGroupAccess::destroy($ids);
                    }
                }
                Member::commit();
            } catch (\Exception $e) {
                Member::rollback();
                return $this->error('删除失败', ['errorMsg' => $e->getMessage()]);
            }
            return $this->success();
        }
    }


    /**
     * 退出登录
     */
    public function loginOut()
    {
        $admin = $this->request->user;
        $scopes = $this->request->scopes;
        if ($this->request->isPost()) {
            $user = Member::find($admin['id']);
//            if($user){
//                $user['token'] = null;
//                $res1 = $user->save();
//            }
            $token = $this->request->server('HTTP_TOKEN', cookie('token'));  //TODO：改变顺序 头 -- cookie -- session -- 参数
            //如果不存在，往session中取
            if (!$token) $token = UserService::getLogin('token');
            //如果不存在，往参数中取
            if (!$token) $token = $this->request->param('token');
            if (!$token) return $this->error('已退出登录，勿重复点击');

            $res = Token::deleteToken($token, $admin['id'], $scopes, true);
            if (!$res) {
                return $this->error(Token::getError('操作失败'));
            } else {
                //return redirect('/manage/member.login');
                return $this->success('退出成功');
            }
        }

    }

    /**
     * 更改开启状态
     *
     * @return \think\Response
     */
    public function setStatus()
    {
        $member_id = $this->uid;

        $Member = Member::getTop($member_id);
        if ($member_id != $Member['id']) return $this->error('子租户无权操作');
        if (request()->isAjax()) {
            $id = input('id/d');
            $data = Member::where('parent_id', $Member['id'])->find($id);
            if ($data['status'] === 0) {
                $data['status'] = 1;
            } elseif ($data['status'] === 1) {
                $data['status'] = 0;
            };
            $data->save();
            return $this->success('successful');

        }
    }

    /**
     * 租户基本资料
     */
    public function userSetting()
    {
        if ($this->request->isPost()) {
            $param = $this->request->param();
            //解绑微信
            if (isset($param['unbind'])) {
                //$user = \app\common\model\Member::find($this->uid);
                //var_dump($this->user);die;
                $this->user->openid = null;
                $this->user->save();
                return $this->success('解绑成功');
            }

            !isset($param['id']) && $param['id'] = (string)$this->uid;

            try {
                if(isset($param['mobile'])) unset($param['mobile']);
                $result = Member::updateAdmin($param, true);
                if ($result) {
                    return $this->success('操作成功');
                } else {
                    return $this->error(Member::getError());
                }
            }catch (\Exception $e){
                return $this->error($e->getFile() . '-' .$e->getLine() . '-' .$e->getMessage());
            }
        }
        $data = \app\common\model\Member::with('wallet')->hidden(['password', 'safe_password'])->find($this->uid);
        $this->layout && $this->app->view->engine()->layout($this->layout);
        return $this->fetch('user_setting', ['data' => $data]);

    }

    public function userPassword()
    {
        if ($this->request->isPost()) {
            $param = $this->request->param();
            $result = Member::updatePassword($param, true);
            if ($result) {
                //如果变更了操作密码
                if (isset($result['password']) && $result['password']) {

                }
                return $this->success('操作成功', $result);
            } else {
                return $this->error(Member::getError());
            }
        }
        $data = AuthGroupAccess::getMemberFind($this->uid);
        return view('user_password', ['data' => $data]);

    }


}
